<?php

/**
 * UserRecoveryForm class.
 * UserRecoveryForm is the data structure for keeping
 * user recovery form data. It is used by the 'recovery' action of 'UserController'.
 * 
 * @author Hemendra Kumar<hemendra@t9l.com>
 * 
 */
class UserRecoveryForm extends CFormModel {

    public $login_or_email, $user_id;

    /**
     * Declares the validation rules.
     * The rules state that username is required
     * Username should be emauil format
     * Username should exist in user table
     */
    public function rules() {
        return array(
            // Username or Email is required 
            array('login_or_email', 'required'),
            //username should be email format 
            array('login_or_email', 'email', 'message' => Yii::t('recovery', "Incorrect username format")),
            //call function to check username exist in table or not
            array('login_or_email', 'checkexists'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
            'login_or_email' => Yii::t('recovery', "Username or Email"),
        );
    }
    /**
     * Function to check wheather user exist in table or not
     * Will execute at the time of validation 
     */
    public function checkexists($attribute, $params) {
        if (!$this->hasErrors()) {  // we only want to authenticate when no input errors

            $user = User::model()->findByAttributes(array('username' => $this->login_or_email));
            if ($user)
                $this->user_id = $user->id;


            if ($user === null)
                    $this->addError("login_or_email", Yii::t('recovery', "Username is incorrect."));
                
        }
    }

}